package org.mybatis.generator.codegen.mybatis3.xmlmapper.elements.suffix;

import org.mybatis.generator.api.dom.xml.Attribute;
import org.mybatis.generator.api.dom.xml.TextElement;
import org.mybatis.generator.api.dom.xml.VisitableElement;
import org.mybatis.generator.api.dom.xml.XmlElement;
import org.mybatis.generator.codegen.mybatis3.SuffixUtil;
import org.mybatis.generator.codegen.mybatis3.xmlmapper.elements.AbstractXmlElementGenerator;

/*********************************************************
 * 文件名称：SuffixCountByExampleElementGenerator.java
 * 系统名称：cxycloud
 * 模块名称：org.mybatis.generator.codegen.mybatis3.xmlmapper.elements.suffix
 * 功能说明：
 * 开发人员 @author：caoxy
 * 开发时间 @date：2023/8/28 11:02
 * 修改记录：程序版本  修改日期  修改人员  修改单号  修改说明
 *********************************************************/
public class SuffixCountByExampleElementGenerator extends AbstractXmlElementGenerator {


    @Override
    public void addElements(XmlElement parentElement) {
        XmlElement answer = new XmlElement("select"); //$NON-NLS-1$
        answer.addAttribute(new Attribute(
                "id", SuffixUtil.getSuffixMethodName(introspectedTable.getCountByExampleStatementId(),introspectedTable))); //$NON
        // -NLS-1$
        answer.addAttribute(new Attribute("parameterType", "map")); //$NON-NLS-1$
        answer.addAttribute(new Attribute("resultType", "java.lang.Long")); //$NON-NLS-1$ //$NON-NLS-2$
        context.getCommentGenerator().addComment(answer);


        String s = "select 1 from " //$NON-NLS-1$
                + SuffixUtil.addTableNameSuffix(introspectedTable.getAliasedFullyQualifiedTableNameAtRuntime(),introspectedTable);

        VisitableElement foreachSuffix = SuffixUtil.getForeachSuffix(new TextElement(s), getUpdateByExampleIncludeElement());
        answer.addElement(new TextElement("select count(*) from ("));
        answer.addElement(foreachSuffix);
        answer.addElement(new TextElement(")"));

        if (context.getPlugins().sqlMapCountByExampleElementGenerated(answer, introspectedTable)
        && SuffixUtil.isEnableSuffix(introspectedTable)) {
            SuffixUtil.deleteOldElement(parentElement,answer);
            parentElement.addElement(answer);
        }
    }
}

